import jwt
from toutiao import Config


def generate_jwt(payload, expiry, secret=None):
    """
    生成token
    :param payload: 用户信息,字典类型
    :param expiry:  过期时间
    :param secret:  秘钥
    :return: token
    """
    _payload = {
        'exp': expiry
    }

    _payload.update(payload)

    if not secret:
        secret = Config.JWT_SECRET

    token = jwt.encode(_payload, secret, algorithm='HS256')

    return token.decode()


def verify_jwt(token, secret=None):
    """
    验证token
    :param token: 之前发送给客户端的token
    :param secret: 秘钥
    :return: payload
    """

    if secret is None:
        secret = Config.JWT_SECRET

    try:
        payload = jwt.decode(token, secret, algorithms=['HS256'])
    except Exception:
        return None
    else:
        return payload